package com.iqilu.ksd.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.MyMessageAdapter;
import com.iqilu.ksd.bean.MessageBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.UnreadMsgEvent;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Coofee on 2016/10/18.
 */

public class MyMessageActivity extends BaseActivity {

    private int page;
    private ArrayList<MessageBean> list;
    private MyMessageAdapter adapter;

    private TextView tvRight;
    private LigDialog ligDialog;
    private ImageView btLeft;
    private TextView tvTitle;
    private ImageView imgEmpty;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_list);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        adapter = new MyMessageAdapter(this);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        rvList.setAdapter(adapter);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        page = 1;
        getList();
    }

    private void initView() {
        tvRight = getView(R.id.tv_right);
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        imgEmpty = getView(R.id.img_empty);
        imgEmpty.setImageResource(R.drawable.bg_message_empty);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        layLoading = getView(R.id.lay_loading);

        tvTitle.setText(getString(R.string.msg_title));
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvRight.setText(getString(R.string.clear_all));
        tvRight.setTextColor(Color.parseColor("#FFFFFF"));
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clear();
            }
        });
        layLoading.setVisibility(View.VISIBLE);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
    }

    public void del(final int position) {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(this.getString(R.string.msg_del))
                .btnText(this.getString(R.string.cancel), this.getString(R.string.ensure))
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        delMessage(position);
                        dialog.dismiss();
                    }
                }
        );
    }

    private void clear() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(this.getString(R.string.msg_del_all))
                .btnText(this.getString(R.string.cancel), this.getString(R.string.ensure))
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        clearMessage();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void getList() {
        String url = Api.URL_MSG + "?page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                xRefreshView.stopRefresh();
                layLoading.setVisibility(View.GONE);
                if(page == 1){
                    xRefreshView.setVisibility(View.GONE);
                    imgEmpty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                xRefreshView.stopRefresh();
                layLoading.setVisibility(View.GONE);
                SPUtils.setPref(MyMessageActivity.this, UserInfo.MSGCOUNT, 0);
                EventBus.getDefault().post(new UnreadMsgEvent(0));
                ArrayList<MessageBean> result = JSONUtils.requestList(response, "data.data", new TypeToken<ArrayList<MessageBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        imgEmpty.setVisibility(View.VISIBLE);
                        xRefreshView.setVisibility(View.GONE);
                        Toast.makeText(MyMessageActivity.this, R.string.list_empty, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list = result;
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                        readAll();
                    }
                } else {
                    xRefreshView.stopLoadMore();
                    if (result == null || result.size() == 0) {
                        Toast.makeText(MyMessageActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list.addAll(result);
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void delMessage(final int position) {
        int id = list.get(position).getId();
        String url = Api.URL_CLUE + "?id=" + id;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(MyMessageActivity.this, getString(R.string.deleting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                Toast.makeText(MyMessageActivity.this, R.string.pk_del_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                JSONObject jsonObject = null;
                int status = 0;
                try {
                    jsonObject = new JSONObject(response);
                    status = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (status == 1) {
                    list.remove(position);
                    adapter.setData(list);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MyMessageActivity.this, R.string.pk_del_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MyMessageActivity.this, R.string.pk_del_fail, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void readAll() {
        String url = Api.URL_MSG_ALL;
        OkHttpUtils.put().url(url).requestBody(RequestBody.create(null, "something")).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                SPUtils.setPref(MyMessageActivity.this, UserInfo.MSGCOUNT, 0);
                EventBus.getDefault().post(new UnreadMsgEvent(0));
            }
        });
    }

    private void clearMessage() {
        String url = Api.URL_MSG_CLEAR;
        OkHttpUtils.delete().url(url).requestBody(RequestBody.create(null, "something")).tag(this).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(MyMessageActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                Toast.makeText(MyMessageActivity.this, R.string.msg_clear_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                int status;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(MyMessageActivity.this, R.string.msg_clear_success, Toast.LENGTH_SHORT).show();
                    SPUtils.setPref(MyMessageActivity.this, UserInfo.MSGCOUNT, 0);
                    EventBus.getDefault().post(new UnreadMsgEvent(0));
                    getList();
                } else {
                    Toast.makeText(MyMessageActivity.this, R.string.msg_clear_fail, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
